package com.ruoyi.ftrl.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.ftrl.domain.CommunityInfo;
import com.ruoyi.ftrl.domain.Dto.HeatInfoAvg;
import com.ruoyi.ftrl.domain.Dto.HeatInfoCount;
import com.ruoyi.ftrl.domain.Dto.StationDto;
import com.ruoyi.ftrl.domain.EquipmentHeat;
import com.ruoyi.ftrl.domain.HeatStation;
import com.ruoyi.ftrl.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ruoyi.ftrl.domain.HeatInfo;
import com.ruoyi.ftrl.service.IHeatInfoService;
import org.springframework.web.client.RestTemplate;

/**
 * 热采集数据信息Service业务层处理
 * 
 * @author dihang
 * @date 2024-08-09
 */
@Service
public class HeatInfoServiceImpl implements IHeatInfoService 
{
    @Autowired
    private HeatInfoMapper heatInfoMapper;

    /**
     * 查询热采集数据信息
     * 
     * @param id 热采集数据信息主键
     * @return 热采集数据信息
     */
    @Override
    public HeatInfo selectHeatInfoById(Long id)
    {
        return heatInfoMapper.selectHeatInfoById(id);
    }

    /**
     * 查询热采集数据信息列表
     * 
     * @param heatInfo 热采集数据信息
     * @return 热采集数据信息
     */
    @Override
    public List<HeatInfo> selectHeatInfoList(HeatInfo heatInfo)
    {
        List<HeatInfo> heatInfos = heatInfoMapper.selectHeatInfoList(heatInfo);
        for (HeatInfo info : heatInfos) {
            // 将字符串转换为 BigDecimal 并保留两位小数
            info.setCount(formatToTwoDecimalPlaces(info.getCount()));
            info.setCountFlow(formatToTwoDecimalPlaces(info.getCountFlow()));
            info.setPower(formatToTwoDecimalPlaces(info.getPower()));
            info.setFlow(formatToTwoDecimalPlaces(info.getFlow()));

            //温差 Field2
            BigDecimal subtract = info.getInletTemp().subtract(info.getOutTemp());
            String cha = String.valueOf(subtract.toString());
            info.setField1(cha);
        }
        return heatInfos;
    }
    /**
     * 将字符串格式化为保留两位小数的字符串
     * @param value 字符串值
     * @return 保留两位小数的字符串
     */
    private String formatToTwoDecimalPlaces(String value) {
        if (value != null && !value.isEmpty()) {
            try {
                BigDecimal decimalValue = new BigDecimal(value);
                return decimalValue.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            } catch (NumberFormatException e) {
                // 处理转换异常，例如记录日志
                return "0.00"; // 或者返回 null，根据需求
            }
        }
        return "0.00"; // 或者返回 null，根据需求
    }

    /**
     * 将字符串转换为 BigDecimal
     * @param value 字符串值
     * @return BigDecimal 值
     */
    private BigDecimal convertToBigDecimal(String value) {
        if (value != null && !value.isEmpty()) {
            try {
                return new BigDecimal(value);
            } catch (NumberFormatException e) {
                // 处理转换异常，例如记录日志
                return BigDecimal.ZERO; // 或者返回 null，根据需求
            }
        }
        return BigDecimal.ZERO; // 或者返回 null，根据需求
    }

    /**
     * 新增热采集数据信息
     * 
     * @param heatInfo 热采集数据信息
     * @return 结果
     */
    @Override
    public int insertHeatInfo(HeatInfo heatInfo)
    {
        heatInfo.setCreateTime(DateUtils.getNowDate());
        return heatInfoMapper.insertHeatInfo(heatInfo);
    }

    /**
     * 修改热采集数据信息
     * 
     * @param heatInfo 热采集数据信息
     * @return 结果
     */
    @Override
    public int updateHeatInfo(HeatInfo heatInfo)
    {
        heatInfo.setUpdateTime(DateUtils.getNowDate());
        return heatInfoMapper.updateHeatInfo(heatInfo);
    }

    /**
     * 批量删除热采集数据信息
     * 
     * @param ids 需要删除的热采集数据信息主键
     * @return 结果
     */
    @Override
    public int deleteHeatInfoByIds(Long[] ids)
    {
        return heatInfoMapper.deleteHeatInfoByIds(ids);
    }

    /**
     * 删除热采集数据信息信息
     * 
     * @param id 热采集数据信息主键
     * @return 结果
     */
    @Override
    public int deleteHeatInfoById(Long id)
    {
        return heatInfoMapper.deleteHeatInfoById(id);
    }
    @Autowired
    private CommunityInfoMapper communityInfoMapper;
    @Autowired
    private HeatStationMapper heatStationMapper;
    /**
     * 供回水温度（大屏驾驶舱）
     * @return
     */

        @Override
        public List<StationDto> selectHeatInfoListHot() {
            List<HeatStation> heatStationList = heatStationMapper.selectHeatStationList(new HeatStation());
            List<StationDto> stationDtos = new ArrayList<>();

            // 批量查询所有小区的热量表信息
            List<Long> heatStationIds = heatStationList.stream().map(HeatStation::getId).collect(Collectors.toList());
            Map<Long, List<CommunityInfo>> communityInfoMap = new HashMap<>();
            Map<String, Long> heatInfoCountMap = new HashMap<>();
            Map<String, Double> avgInMap = new HashMap<>();
            Map<String, Double> avgOutMap = new HashMap<>();

            // 获取所有小区信息
            for (HeatStation heatInfo : heatStationList) {
                List<CommunityInfo> communityInfoList = communityInfoMapper.selectCommunityInfoLists(heatInfo.getId());
                communityInfoMap.put(heatInfo.getId(), communityInfoList);
            }

            // 批量查询热量表数量
            List<String> communityNames = communityInfoMap.values().stream()
                    .flatMap(List::stream)
                    .map(CommunityInfo::getName)
                    .collect(Collectors.toList());

            // 查询热量表数量
            Map<String, Long> countMap = heatInfoMapper.selectCountBatch(communityNames).stream()
                    .collect(Collectors.toMap(HeatInfoCount::getVillageName, HeatInfoCount::getCount));

            // 批量查询每个小区的平均供水和回水温度
            Map<String, Double[]> avgTempMap = heatInfoMapper.selectHeatInfoBatch(communityNames).stream()
                    .collect(Collectors.toMap(HeatInfoAvg::getVillageName, avg -> new Double[]{avg.getAvgIn(), avg.getAvgOut()}));

            // 计算每个热力站的平均供水和回水温度
            for (HeatStation heatInfo : heatStationList) {
                StationDto stationDto = new StationDto();
                stationDto.setName(heatInfo.getName());

                List<CommunityInfo> communityInfoList = communityInfoMap.get(heatInfo.getId());
                if (communityInfoList != null && !communityInfoList.isEmpty()) {
                    double totalIn = 0.0;
                    double totalOut = 0.0;
                    int count = 0;

                    for (CommunityInfo communityInfo : communityInfoList) {
                        String name = communityInfo.getName();
                        if (countMap.containsKey(name) && countMap.get(name) > 0) {
                            Double[] avgTemps = avgTempMap.get(name);
                            if (avgTemps != null) {
                                totalIn += avgTemps[0];
                                totalOut += avgTemps[1];
                                count++;
                            }
                        }
                    }

                    if (count > 0) {
                        stationDto.setIntemp(String.valueOf(totalIn / count));
                        stationDto.setOuttemp(String.valueOf(totalOut / count));
                    } else {
                        stationDto.setIntemp("--");
                        stationDto.setOuttemp("--");
                    }
                } else {
                    stationDto.setIntemp("--");
                    stationDto.setOuttemp("--");
                }

                stationDtos.add(stationDto);
            }

            return stationDtos;
        }

//    @Override
//    public List<StationDto> selectHeatInfoListHot() {
//        List<HeatStation> heatStationList = heatStationMapper.selectHeatStationList(new HeatStation());
//        List<StationDto> stationDtos = new ArrayList<StationDto>();
//        for (HeatStation heatInfo : heatStationList) {
//            StationDto stationDto = new StationDto();
//            //热力站名称
//            stationDto.setName(heatInfo.getName());
//            //平均供水温度
//            //热力站下的所有小区
//            List<CommunityInfo> communityInfoList = communityInfoMapper.selectCommunityInfoLists(heatInfo.getId());
//            if (communityInfoList != null && !communityInfoList.isEmpty()){
//                //查看该小区下有没有热量表
//                List<String> list = communityInfoList.stream().map(CommunityInfo::getName).toList();
//                for (String string : list) {
//                    Long count=heatInfoMapper.selectCount(string);
//                    if (count==0){
//                        stationDto.setIntemp("--");
//                        stationDto.setOuttemp("--");
//
//                    }else {
//                        double in=0.0;
//                        double out=0.0;
//                        for (CommunityInfo communityInfo : communityInfoList) {
//                            String name = communityInfo.getName();
//                            //一个小区所有的热表信息数据
//                            double avgIn=heatInfoMapper.selectHeatInfoByName(name);
//                            in+=avgIn;
//                            double avgOut=heatInfoMapper.selectHeatInfoByNames(name);
//                            out+=avgOut;
//
//                        }
//                        //对数据的供水温度进行求平均值
//                        double v = in / communityInfoList.size();
//                        //平均供水温度
//                        stationDto.setIntemp(String.valueOf(v));
//
//                        //对数据的回水温度进行求平均值
//                        double o = out / communityInfoList.size();
//                        //平均供水温度
//                        stationDto.setOuttemp(String.valueOf(o));
////                    stationDtos.add(stationDto);
//                    }
//
//                }
//            }else {//热力站下无关联小区
//                stationDto.setIntemp("--");
//                stationDto.setOuttemp("--");
//            }
//
//            stationDtos.add(stationDto);
//
//        }
//
//        return stationDtos;
//    }

@Autowired
private EquipmentHeatMapper equipmentHeatMapper;
    /**
     * 定时拉取天罡系统关于安悦佳苑的热表数据
     * @return
     */
    @Override
    public Object selectHeatInfoLists() {
        //获取token值
        String token = getToken();
        if (token != null) {
//            String url = "<接口网址>/extends/userRunningData/getMeterDataNow"; // replace with actual URL
//            String requestBody = "{\"type\": \"meterNo\", \"page\": \"1\", \"pageSize\": \"2000\", \"meterNo\": \"42345678\"}";
            String url = "http://yun.plou.cn:17608/extends/userRunningData/getMeterDataNowNormal";
            String requestBody = "{\"type\": \"all\", \"page\": \"1\", \"pageSize\": \"2000\"}";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("charset", "UTF-8");
            headers.set("access_token", token);
            headers.set("client_id", "baodingfatouInterface");

            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            try {
                ObjectMapper mapper = new ObjectMapper();
                JsonNode dataNode = mapper.readTree(response.getBody()).get("data");

                for (JsonNode node : dataNode) {
                    HeatInfo heatInfo = new HeatInfo();
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String sysReadTime = node.get("sysReadTime").asText();
                    if (!sysReadTime.isEmpty()){
                        Date parse = df.parse(sysReadTime);
                        heatInfo.setTime(parse);
                    }
                    //                    heatInfo.setAllTime(node.get("allTime").asText());
//                    heatInfo.setMsg(node.get("msg").asText());
//                  heatInfo.setHouseId(node.get("houseId").asText());
//                    heatInfo.setOutFlow(node.get("outFlow").asDouble());
//                    heatInfo.setFlowSpeed(node.get("flowSpeed").asDouble());
//                    heatInfo.setCool(node.get("cool").asDouble());
//                    heatInfo.setPower(node.get("power").asDouble());
                    heatInfo.setDeviceCode(node.get("address2nd").asText());
                    heatInfo.setCount(String.valueOf(node.get("heat").asDouble()));
                    heatInfo.setCountFlow(String.valueOf(node.get("inFlow").asDouble()));
                    heatInfo.setInletTemp(BigDecimal.valueOf(node.get("inTemperature").asDouble()));
                    heatInfo.setOutTemp(BigDecimal.valueOf(node.get("outTemperature").asDouble()));
                    heatInfo.setCountWork(node.get("allWorkTime").asText());
//                    heatInfoMapper.insertHeatInfo(heatInfo);
                    EquipmentHeat equipmentHeat = equipmentHeatMapper.selectEquipmentHeatByCode(heatInfo.getDeviceCode());
                    if (equipmentHeat != null){
                        //小区
                        heatInfo.setVillageName(equipmentHeat.getCommunityName());
                        //楼栋
                        heatInfo.setBuildingName(equipmentHeat.getBuildingName());
                        //单元
                        heatInfo.setUnitName(equipmentHeat.getUnitName());
                        //房间号
                        heatInfo.setRoomName(equipmentHeat.getRoomAme());
                        heatInfo.setDeviceCode(equipmentHeat.getNodeId());
                        heatInfo.setRoomNo(equipmentHeat.getRoomNo());
                        heatInfo.setManufactor("2");
                        heatInfo.setCreateTime(new Date());
                        heatInfo.setHistory("1");
                        heatInfo.setState("0");


                        HeatInfo heatInfoByCode = heatInfoMapper.selectHeatInfoByCode(heatInfo.getDeviceCode());
                        System.err.println(heatInfo.getDeviceCode());
                        if (heatInfoByCode != null) {
                            //修改为历史记录
                            System.err.println("不为空！！！");
                            heatInfoMapper.updateHeatInfoId(heatInfoByCode.getId());
                            heatInfoMapper.insertHeatInfo(heatInfo);
                        }else {
                            //持久化
                            heatInfoMapper.insertHeatInfo(heatInfo);
                        }
                    }

                }
                return dataNode.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
return null;
    }

    private final RestTemplate restTemplate = new RestTemplate();
    private String getToken() {
        String tokenUrl = "http://yun.plou.cn/module/oauth/token";
        String params = "?grant_type=client_credentials&client_id=baodingfatouInterface&client_secret=baodingfatouInterface123!";

        ResponseEntity<String> response = restTemplate.getForEntity(tokenUrl + params, String.class);

        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(response.getBody());
            System.err.println(rootNode.path("data").path("access_token").asText());
            return rootNode.path("data").path("access_token").asText();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
